package com.lottery.material.controller.admin.circle;

import com.lottery.material.common.EnumInfo;
import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.enumeration.circle.CircleInfoEnum;
import com.lottery.material.enumeration.circle.CircleMemberInfoEnum;
import com.lottery.material.enumeration.common.CommonEnum;
import com.lottery.material.enumeration.conf.MenuLevelConfigEnum;
import com.lottery.material.enumeration.portaluser.PortalUserInfoEnum;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.circle.CircleMemberInfo;
import com.lottery.material.pojo.conf.MenuLevelConfig;
import com.lottery.material.pojo.page.Page;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.pojocustom.circle.CircleInfoCustom;
import com.lottery.material.pojocustom.portaluser.PortalUserInfoCustom;
import com.lottery.material.service.admin.circle.CircleInfoService;
import com.lottery.material.service.admin.circle.CircleMemberInfoService;
import com.lottery.material.service.admin.conf.MenuLevelConfigService;
import com.lottery.material.service.admin.portaluser.PortalUserInfoService;
import com.lottery.material.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description：圈子信息Controller
 * Created by 朱正磊 on 2019-04-13 20:16
 */
@Slf4j
@Controller("adminCircleInfoController")
@RequestMapping("/admin/circleInfo")
public class CircleInfoController extends BaseController {

    //菜单地址，用于权限控制
    private String menuUrl = "admin/circleInfo/list";

    private final CircleInfoService circleInfoService;

    private final MenuLevelConfigService menuLevelConfigService;

    private final PortalUserInfoService portalUserInfoService;

    private final CircleMemberInfoService circleMemberInfoService;

    @Autowired
    public CircleInfoController(CircleInfoService circleInfoService,
                                MenuLevelConfigService menuLevelConfigService,
                                PortalUserInfoService portalUserInfoService,
                                CircleMemberInfoService circleMemberInfoService) {
        this.circleInfoService = circleInfoService;
        this.menuLevelConfigService = menuLevelConfigService;
        this.portalUserInfoService = portalUserInfoService;
        this.circleMemberInfoService = circleMemberInfoService;
    }

    /**
     * description：分页列表
     * user 朱正磊
     * time 2019-04-17 15:06
     * @param page 分页对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/list")
    public ModelAndView listPage(Page page, Map<String, Object> map) {
        //分页对象设置页面请求参数
        PageData pd = getPageData();
        PdUtil.rePut(pd);
        page.setPd(pd);

        //查询分页列表
        List<CircleInfoCustom> list = circleInfoService.findCustomListPage(page);
        map.put("list", list);
        map.put("pd", pd);
        map.put("QX", Jurisdiction.getHC());

        //所属一级类别（属于圈子菜单）
        List<MenuLevelConfig> menuOneLevelConfigList = menuLevelConfigService.findByLevelTypeAndState(
                (Integer) MenuLevelConfigEnum.LEVEL_TYPE_ONE.getValue(), null,
                (Integer) MenuLevelConfigEnum.IS_CIRCLE_MENU_TRUE.getValue());
        map.put("menuOneLevelConfigList", menuOneLevelConfigList);

        //所属二级类别（属于圈子菜单）
        List<MenuLevelConfig> menuTwoLevelConfigList = menuLevelConfigService.findByLevelTypeAndState(
                (Integer) MenuLevelConfigEnum.LEVEL_TYPE_TWO.getValue(), null,
                (Integer) MenuLevelConfigEnum.IS_CIRCLE_MENU_TRUE.getValue());
        map.put("menuTwoLevelConfigList", menuTwoLevelConfigList);

        //是否标记为热门圈子（1：否；2：是）
        List<EnumInfo> isHotCircleList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_HOT_CIRCLE, CircleInfoEnum.class);
        map.put("isHotCircleList", isHotCircleList);

        //是否进入精彩（1：否；2：是）
        List<EnumInfo> isWonderfulList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_WONDERFUL, CircleInfoEnum.class);
        map.put("isWonderfulList", isWonderfulList);

        //状态（1：上架；2：下架）
        List<EnumInfo> stateList = EnumUtil.getEnumInfoList(CommonEnum.STATE, CommonEnum.class);
        map.put("stateList", stateList);

        return new ModelAndView("circle/circleInfo/listPage", map);
    }

    /**
     * description：详情页面
     * user 朱正磊
     * time 2019-04-17 16:20
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/detailPage")
    public ModelAndView detailPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {//判断是否有查看权限
            return null;
        }

        //根据主键查询扩展类
        CircleInfoCustom circleInfo = circleInfoService.findCustomById(id);
        map.put("circleInfo", circleInfo);

        return new ModelAndView("circle/circleInfo/detailPage", map);
    }

    /**
     * description：添加页面
     * user 朱正磊
     * time 2019-04-17 16:26
     * @param menuTwoLevelId 二级类别ID
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping("/addPage")
    public ModelAndView addPage(Integer menuTwoLevelId, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {//判断是否有添加权限
            return null;
        }

        Integer parentId = null;
        if (AssertUtil.isNotEmpty(menuTwoLevelId)) { // 二级类别创建而来
            //获取二级类别
            MenuLevelConfig menuTwoLevel = menuLevelConfigService.findById(menuTwoLevelId);
            String menuTwoLevelCode = menuTwoLevel.getMenuCode();
            map.put("menuTwoLevelCode", menuTwoLevelCode);

            //获取一级类别
            parentId = menuTwoLevel.getParentId();
            MenuLevelConfig menuOneLevel = menuLevelConfigService.findById(parentId);
            String menuOneLevelCode = menuOneLevel.getMenuCode();
            map.put("menuOneLevelCode", menuOneLevelCode);
        }

        //一级类别列表展示条件：上架并且属于圈子菜单
        List<MenuLevelConfig> menuOneLevelConfigList = menuLevelConfigService.findByLevelTypeAndState(
                (Integer) MenuLevelConfigEnum.LEVEL_TYPE_ONE.getValue(),
                (Integer) CommonEnum.STATE_ON.getValue(),
                (Integer) MenuLevelConfigEnum.IS_CIRCLE_MENU_TRUE.getValue());
        map.put("menuOneLevelConfigList", menuOneLevelConfigList);

        //根据一级类别查询二级类别
        List<MenuLevelConfig> menuTwoLevelConfigList;
        if (AssertUtil.isNotEmpty(parentId)) {
            menuTwoLevelConfigList = menuLevelConfigService
                    .findByParentIdAndState(parentId, (Integer) CommonEnum.STATE_ON.getValue());
        } else {
            menuTwoLevelConfigList = menuLevelConfigService
                    .findByParentIdAndState(menuOneLevelConfigList.get(0).getId(), (Integer) CommonEnum.STATE_ON.getValue());
        }
        map.put("menuTwoLevelConfigList", menuTwoLevelConfigList);

        //查询前端运营用户列表（在后台注册的前端用户）
        List<PortalUserInfoCustom> portalUserInfoList = portalUserInfoService.findPortalUserInfoByLogonMode(
                (Integer) PortalUserInfoEnum.LOGON_MODE_ADMIN.getValue(),
                (Integer) PortalUserInfoEnum.USER_STATUS_NORMAL.getValue());
        for (PortalUserInfoCustom portalUserInfo : portalUserInfoList) {
            String nickName = portalUserInfo.getNickName();
            String userId = portalUserInfo.getUserId();
            //根据用户id查询圈子成员列表
            List<CircleMemberInfo> circleMemberInfoList = circleMemberInfoService.findByUserId(userId);
            //用户拥有的圈子成员个数其实就是用户拥有的圈子个数
            int size = circleMemberInfoList.size();
            portalUserInfo.setNameShow(nickName + "(" + size + ")");
        }
        map.put("portalUserInfoList", portalUserInfoList);

        //是否标记为热门圈子（1：否；2：是）
        List<EnumInfo> isHotCircleList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_HOT_CIRCLE, CircleInfoEnum.class);
        map.put("isHotCircleList", isHotCircleList);

        //是否进入精彩（1：否；2：是）
        List<EnumInfo> isWonderfulList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_WONDERFUL, CircleInfoEnum.class);
        EnumInfo isWonderfulEnumInfo0 = isWonderfulList.get(0);
        EnumInfo isWonderfulEnumInfo1 = isWonderfulList.get(1);
        isWonderfulList.set(0, isWonderfulEnumInfo1);
        isWonderfulList.set(1, isWonderfulEnumInfo0);
        map.put("isWonderfulList", isWonderfulList);

        //是否禁止评论（1：否；2：是）
        List<EnumInfo> isProhibitionCommentList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_PROHIBITION_COMMENT, CircleInfoEnum.class);
        map.put("isProhibitionCommentList", isProhibitionCommentList);

        //是否禁止发贴（1：否；2：是）
        List<EnumInfo> isProhibitionPublishList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_PROHIBITION_PUBLISH, CircleInfoEnum.class);
        map.put("isProhibitionPublishList", isProhibitionPublishList);

        //添加请求地址
        map.put("actionUrl", "admin/circleInfo/add");

        return new ModelAndView("circle/circleInfo/editPage", map);
    }

    /**
     * description：添加
     * user 朱正磊
     * time 2019-04-17 16:39
     * @param request 请求对象
     * @param circleInfo 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/add")
    public ModelAndView add(HttpServletRequest request, CircleInfo circleInfo, Map<String, Object> map) {
        Integer flag = circleInfoService.add(request, circleInfo);
        if (Objects.equals(flag, 0)) { //添加失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：修改页面
     * user 朱正磊
     * time 2019-04-17 16:48
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping("/editPage")
    public ModelAndView editPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }

        //根据主键查询扩展类
        CircleInfoCustom circleInfo = circleInfoService.findCustomById(id);
        map.put("circleInfo", circleInfo);

        //查询前端运营用户列表（在后台注册的前端用户）
        List<PortalUserInfoCustom> portalUserInfoList = portalUserInfoService.findPortalUserInfoByLogonMode(
                (Integer) PortalUserInfoEnum.LOGON_MODE_ADMIN.getValue(),
                (Integer) PortalUserInfoEnum.USER_STATUS_NORMAL.getValue());
        for (PortalUserInfoCustom portalUserInfo : portalUserInfoList) {
            String nickName = portalUserInfo.getNickName();
            String userId = portalUserInfo.getUserId();
            //根据用户id查询圈子成员列表
            List<CircleMemberInfo> circleMemberInfoList = circleMemberInfoService.findByUserId(userId);
            //用户拥有的圈子成员个数其实就是用户拥有的圈子个数
            int size = circleMemberInfoList.size();
            portalUserInfo.setNameShow(nickName + "(" + size + ")");
        }
        map.put("portalUserInfoList", portalUserInfoList);

        //获取用户id（根据圈子id和等级为圈主可以确定唯一一条数据）
        List<CircleMemberInfo> circleMemberInfoList = circleMemberInfoService.findByCircleIdAndRank(circleInfo.getId(),
                (Integer) CircleMemberInfoEnum.RANK_MAIN.getValue());
        map.put("userId", circleMemberInfoList.get(0).getUserId());

        //获取二级类别
        map.put("menuTwoLevelCode", circleInfo.getSubTypeCode());

        //获取一级类别
        map.put("menuOneLevelCode", circleInfo.getMainTypeCode());

        //一级类别列表展示条件：上架并且属于圈子菜单
        List<MenuLevelConfig> menuOneLevelConfigList = menuLevelConfigService.findByLevelTypeAndState(
                (Integer) MenuLevelConfigEnum.LEVEL_TYPE_ONE.getValue(),
                (Integer) CommonEnum.STATE_ON.getValue(),
                (Integer) MenuLevelConfigEnum.IS_CIRCLE_MENU_TRUE.getValue());
        map.put("menuOneLevelConfigList", menuOneLevelConfigList);

        //根据一级类别查询二级类别
        MenuLevelConfig parent = menuLevelConfigService.findByMenuCode(circleInfo.getMainTypeCode());
        List<MenuLevelConfig> menuTwoLevelConfigList = menuLevelConfigService
                .findByParentIdAndState(parent.getId(), (Integer) CommonEnum.STATE_ON.getValue());
        map.put("menuTwoLevelConfigList", menuTwoLevelConfigList);

        Integer sendInterval = circleInfo.getSendInterval();
        if (AssertUtil.isNotEmpty(sendInterval)) {
            //发帖间隔限制时
            Integer total = sendInterval / 60; //总共多少分
            Integer hour = total / 60; //多少小时
            map.put("hour", hour);
            //发帖间隔限制分
            Integer minute = total % 60; //多少分钟
            map.put("minute", minute);
        }

        //是否标记为热门圈子（1：否；2：是）
        List<EnumInfo> isHotCircleList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_HOT_CIRCLE, CircleInfoEnum.class);
        map.put("isHotCircleList", isHotCircleList);

        //是否进入精彩（1：否；2：是）
        List<EnumInfo> isWonderfulList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_WONDERFUL, CircleInfoEnum.class);
        map.put("isWonderfulList", isWonderfulList);

        //是否禁止评论（1：否；2：是）
        List<EnumInfo> isProhibitionCommentList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_PROHIBITION_COMMENT, CircleInfoEnum.class);
        map.put("isProhibitionCommentList", isProhibitionCommentList);

        //是否禁止发贴（1：否；2：是）
        List<EnumInfo> isProhibitionPublishList = EnumUtil
                .getEnumInfoList(CircleInfoEnum.IS_PROHIBITION_PUBLISH, CircleInfoEnum.class);
        map.put("isProhibitionPublishList", isProhibitionPublishList);

        //修改请求地址
        map.put("actionUrl", "admin/circleInfo/edit");

        return new ModelAndView("circle/circleInfo/editPage", map);
    }

    /**
     * description：修改
     * user 朱正磊
     * time 2019-04-17 16:58
     * @param request 请求对象
     * @param circleInfo 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/edit")
    public ModelAndView edit(HttpServletRequest request, CircleInfo circleInfo, Map<String, Object> map) {
        Integer flag = circleInfoService.updateById(request, circleInfo);
        if (Objects.equals(flag, 0)) { //修改失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：上架或者下架
     * user 朱正磊
     * time 2019-04-21 18:57
     * @param id 主键id
     * @param state 上下架：1上架；2下架
     * @return 返回响应对象
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping("/onOrOff")
    @ResponseBody
    public ResponseResult onOrOff(Integer id, Integer state) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }
        CircleInfo circleInfo = circleInfoService.findById(id);
        final String name = "该圈子";
        if (Objects.equals(CommonEnum.STATE_ON.getValue(), state)) { //进行下架
            circleInfo.setState((Integer) CommonEnum.STATE_OFF.getValue());
            Integer flag = circleInfoService.updateById(null, circleInfo);
            if (flag == 0) {
                return ResponseResult.buildFormatResult(ResultEnum.ADMIN_OFF_FAILURE, name);
            }
            return ResponseResult.buildFormatResult(ResultEnum.ADMIN_OFF_SUCCESS, name);
        } else { //进行上架
            //判断所属的二级类别有没有上架
            String subTypeCode = circleInfo.getSubTypeCode();
            MenuLevelConfig menuLevelConfig = menuLevelConfigService.findByMenuCode(subTypeCode);
            Integer mState = menuLevelConfig.getState();
            if (Objects.equals(mState, CommonEnum.STATE_OFF.getValue())) {
                return ResponseResult.buildResult(400, "请您先上架该圈子所属的二级类别！");
            }
            //正常上架
            circleInfo.setState((Integer) CommonEnum.STATE_ON.getValue());
            Integer flag = circleInfoService.updateById(null, circleInfo);
            if (flag == 0) {
                return ResponseResult.buildFormatResult(ResultEnum.ADMIN_ON_FAILURE, name);
            }
            return ResponseResult.buildFormatResult(ResultEnum.ADMIN_ON_SUCCESS, name);
        }
    }

    /**
     * description：批量上架
     * user 朱正磊
     * time 2019-04-24 16:17
     * @param ids 主键集合(多个id以,进行拼接)
     * @return 返回响应对象
     */
    @RequestMapping("/batchOn")
    @ResponseBody
    public ResponseResult batchOn(String ids) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }
        Integer flag = circleInfoService.updateBatchOn(ids);
        if (Objects.equals(flag, 0)) {
            return ResponseResult.buildResult(400, "批量上架失败");
        } else {
            return ResponseResult.buildResult(200, "批量上架成功");
        }
    }

    /**
     * description：批量下架
     * user 朱正磊
     * time 2019-04-24 16:17
     * @param ids 主键集合(多个id以,进行拼接)
     * @return 返回响应对象
     */
    @RequestMapping("/batchOff")
    @ResponseBody
    public ResponseResult batchOff(String ids) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }
        Integer flag = circleInfoService.updateBatchOff(ids);
        if (Objects.equals(flag, 0)) {
            return ResponseResult.buildResult(400, "批量下架失败");
        } else {
            return ResponseResult.buildResult(200, "批量下架成功");
        }
    }

    /**
     * description：批量选入精彩页面
     * user 朱正磊
     * time 2019-04-24 16:18
     * @param ids 主键集合(多个id以,进行拼接)
     * @return 返回响应对象
     */
    @RequestMapping("/batchIsWonderful")
    @ResponseBody
    public ResponseResult batchIsWonderful(String ids) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }
        Integer flag = circleInfoService.updateBatchIsWonderful(ids);
        if (Objects.equals(flag, 0)) {
            return ResponseResult.buildResult(400, "批量选入精彩页面失败");
        } else {
            return ResponseResult.buildResult(200, "批量选入精彩页面成功");
        }
    }

    /**
     * description：批量撤出精彩页面
     * user 朱正磊
     * time 2019-04-24 16:18
     * @param ids 主键集合(多个id以,进行拼接)
     * @return 返回响应对象
     */
    @RequestMapping("/batchIsNotWonderful")
    @ResponseBody
    public ResponseResult batchIsNotWonderful(String ids) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }
        Integer flag = circleInfoService.updateBatchIsNotWonderful(ids);
        if (Objects.equals(flag, 0)) {
            return ResponseResult.buildResult(400, "批量撤出精彩页面失败");
        } else {
            return ResponseResult.buildResult(200, "批量撤出精彩页面成功");
        }
    }

    /**
     * description：验证圈子名称不能重复（不能跟一级类别、二级类别、其他圈子名称重复）
     * user 朱正磊
     * time 2019-04-25 15:20
     * @param request 请求对象
     * @return 返回响应对象
     */
    @RequestMapping("/validateSameName")
    @ResponseBody
    public ResponseResult validateSameName(HttpServletRequest request) {
        String name = request.getParameter("circleName");
        name = name.trim();//去两端空格
        //根据圈子名称查询圈子列表（可以不存在，如果存在只允许存在一条数据）
        List<CircleInfo> circleInfoList = circleInfoService.findByCircleName(name);
        int circleInfoSize = circleInfoList.size();

        //根据类别名称查询类别列表（可以不存在，如果存在只允许存在一条数据）
        List<MenuLevelConfig> menuLevelConfigList = menuLevelConfigService.findByMenuName(name);
        int menuLevelConfigSize = menuLevelConfigList.size();

        //如果类别或者圈子已存在一条相同名称的数据就不允许再次出现
        if (Objects.equals(circleInfoSize, 1) || Objects.equals(menuLevelConfigSize, 1)) {
            return ResponseResult.buildResult(400, "该名称已存在，请填写其他名称！");
        }

        return ResponseResult.buildResult(200);
    }

}
